import { Logger } from "../../../common/log/Logger";
import { InjectableObject, ModelOptions } from "../../../inject";
import { INJECT_MODEL_LIST_TAG } from "../../../inject/typed/injector-typed";
import BaseModel from "../../base/BaseModel";
import { BasePresenter } from "../../base/BasePresenter";


export interface IPresenterProxy {
    injectModels(): void;
    detachModels(): void;
}


export default class PresenterMvpProxy extends InjectableObject implements IPresenterProxy {
    private _models: BaseModel[];
    private _presenter: BasePresenter<any>;

    constructor(presenter: BasePresenter<any>) {
        super();
        this._presenter = presenter;
        this._models = [];
    }

    public injectModels() {
        let ModelList = Reflect.get(this._presenter, INJECT_MODEL_LIST_TAG);
        if (ModelList) {
            ModelList.forEach((element: ModelOptions) => {
                /**
                 * Injectable修饰的类，已注入到注册器
                 * 否则，不在注入器中
                 */
                let model: BaseModel = this.injector.getInstance(element.propertyType.name)
                if (!model)
                    model = this.injector.instantiateOf(element.propertyType);

                this._presenter[element.propertyName] = model;
                this._models.push(model);

                model.attach();

                Logger.debug("inject model: ", element.propertyName)
            });
        }
    }

    public detachModels() {
        this._models.forEach(model => {
            model.detach();
        })
    }
}
